import axios from 'src/axios'

/**
 * URL地址
 * @param {*} s
 */
// const isURL = (s) => {
//   return /^http[s]?:\/\/.*/.test(s)
// }

/**
 * AJAX 请求
 * @param {string} method
 * @param {string} url
 * @param {Object} data
 */
export const ajaxData = (method, url, data) => axios({ method, url, data })

/**
 * DELETE 请求
 * @param {string} api
 * @param {Object} params
 * @param {function(Object): void} success
 * @param {function(Object): void} error
 */
export function deleteAPI (api, params, success, error = void 0) {
  ajaxData('delete', api, params).then(res => {
    success && success(res)
  }).catch(err => {
    error && error(err)
  })
}

/**
 * GET 请求
 * @param {string} api
 * @param {Object} params
 * @param {function(Object): void} success
 * @param {function(Object): void} error
 */
export function getAPI (api, params, success, error = void 0) {
  ajaxData('get', api, params).then(res => {
    success && success(res)
  }).catch(err => {
    error && error(err)
  })
}

/**
 * POST 请求
 * @param {string} api
 * @param {Object} params
 * @param {function(Object): void} success
 * @param {function(Object): void} error
 */
export function postAPI (api, params, success, error = void 0) {
  ajaxData('post', api, params).then(res => {
    success && success(res)
  }).catch(err => {
    error && error(err)
  })
}

/**
 * PUT 请求
 * @param {string} api
 * @param {Object} params
 * @param {function(Object): void} success
 * @param {function(Object): void} error
 */
export function putAPI (api, params, success, error = void 0) {
  ajaxData('put', api, params).then(res => {
    success && success(res)
  }).catch(err => {
    error && error(err)
  })
}

/**
 * 异步 AJAX 请求
 * @param {string} method
 * @param {string} url
 * @param {Object} data
 */
export const awaitAjaxData = async (method, url, data) => await axios({ method, url, data })

/**
 * 异步 POST 请求
 * @param {string} api
 * @param {Object} params
 * @param {function(Object): void} success
 * @param {function(Object): void} error
 */
export const awaitPostAPI = async (api, params, success, error = void 0) => {
  await awaitAjaxData('post', api, params).then(res => {
    success && success(res)
  }).catch(err => {
    error && error(err)
  })
}
/**
 * 异步 GET 请求
 * @param {string} api
 * @param {Object} params
 * @param {function(Object): void} success
 * @param {function(Object): void} error
 */
export const awaitGetAPI = async (api, params, success, error = void 0) => {
  await awaitAjaxData('get', api, params).then(res => {
    success && success(res)
  }).catch(err => {
    error && error(err)
  })
}